﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ParkManagement
{
    /// <summary>
    /// 停车场应用服务类
    /// </summary>
    public class LotAppService : ApplicationService, ILotAppService
    {
        private readonly IRepository<Lot, int> _lotRepository;

        public LotAppService(
            IRepository<Lot, int> lotRepository)
        {
            _lotRepository = lotRepository;
        }

        // 列表
        public async Task<ListResponse<LotDto>> PagedListAsync(PagedListRequest request, string address, string open, string parkName)
        {
            // 数据筛选
            var query = await _lotRepository.GetQueryableAsync();
            query = query.WhereIf(!string.IsNullOrWhiteSpace(address), m => m.Address.Contains(address));
            query = query.WhereIf(!string.IsNullOrWhiteSpace(open), m => m.Open == (SystemWhether)Enum.Parse(typeof(SystemWhether), open));
            query = query.WhereIf(!string.IsNullOrWhiteSpace(parkName), m => m.ParkName.Contains(parkName));
            // 计数
            var count = query.Count();
            // 排序
            if (!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Lot>, List<LotDto>>(list);
            return ListResponse<LotDto>.Successful(count, dtos);
        }

        // 详情
        public async Task<ResultResponse<LotDto>> GetAsync(int id)
        {
            var lot = await _lotRepository.GetAsync(id);
            var dto = ObjectMapper.Map<Lot, LotDto>(lot);
            return ResultResponse<LotDto>.Successful(dto);
        }
    }
}